const jwt = require('jsonwebtoken') // 引入jsonwebtoken模块
const cert = 'vmore-sugarscat-113Bmongojsdalkfnxcvmas'

class Jwt {
    // 获取调用方法的传值
    constructor() {}
    // 生成token
    generateToken (data) {
        // 获取时间转成时间戳
        let created = new Date().getTime()
        let token = jwt.sign({
            token :data,
            validityTime: created + 86400000,// 自定义token 的有效时间 24 h
        }, cert, { algorithm: 'HS256' })
        return token
    }
    // 校验token
    verifyToken (token) {
        try {
            // 解密生成的token
            const result = jwt.verify(token, cert, { algorithms: ['HS256'] }) || {}
            // 获取生成token的时间
            const { validityTime } = result
            // 获取当前时间
            const current = new Date().getTime()
            // 判断是否失效
            if (current <= validityTime) {
                return true
            } else {
                return false
            }
        } catch (err) {
            return false
        }
    }
}

function generateToken(data) {
    let jwtOne = new Jwt
    let token = jwtOne.generateToken(data)
    return token
}

function verifyToken(token) {
    let jwtOne = new Jwt
    return jwtOne.verifyToken(token)
}


exports.generateToken = generateToken;
exports.verifyToken = verifyToken;